package com.ncs.base.task.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.quartz.Calendar;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ncs.base.common.rule.DateUtil;
import com.ncs.base.common.rule.JobUtils;
import com.ncs.base.task.config.RemindJob;
import com.ncs.base.task.config.UserJob;
import com.ncs.base.task.dao.slave.TimedTaskDao;
import com.ncs.base.task.entity.AddRequest;
import com.ncs.base.task.entity.ResultBO;
import com.ncs.base.task.entity.TaskEntity;
import com.ncs.base.task.entity.TimeTaskEntity;
import com.ncs.base.task.service.TaskService;
import com.ncs.base.task.service.TimedTaskService;

@Service("timedTaskService")
public class TimedTaskServiceImpl extends ServiceImpl<TimedTaskDao, TimeTaskEntity> implements TimedTaskService {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @Autowired
    private TaskService taskService;

   // @Autowired
   // private TimedTaskDao timedTaskMapper;

    @Override
    public ResultBO addQuartzJob(AddRequest addRequest) {

        ResultBO resultBO = new ResultBO();
        TaskEntity task = taskService.selectById(addRequest.getTaskId());

        if(null == task){
            resultBO.setCode(400);
            resultBO.setMsg("请核对任务id是否正确!");
            resultBO.setSucceed(false);
            return resultBO;
        }
        resultBO = addQuartz(addRequest, task);
        return resultBO;
    }

    /**
     * 删除定时任务
     * @param taskId
     * @return
     */
    @Override
    public ResultBO deleteQuartzJob(Integer taskId) throws Exception {

        ResultBO resultBO = new ResultBO();
        TaskEntity task = taskService.selectById(taskId);

        if(null == task){
            resultBO.setCode(400);
            resultBO.setMsg("请核对任务id是否正确!");
            resultBO.setSucceed(false);
            return resultBO;
        }
        resultBO = deleteQuartz(task);

        return resultBO;
    }

    /**
     * 删除timedTask中的数据
     * @param taskId
     */
    private void deleteByTaskId(Integer taskId) {
        this.deleteByTaskId(taskId);
    }

    /**
     * 添加定时任务
     * @param request
     * @param task
     */
    public ResultBO addQuartz(AddRequest request, TaskEntity task) {

        try {
            addOneTime(request, task);
            //addTwoTime(request, task);
            //addThirdTime(request, task);

            return ResultBO.success("添加定时任务成功!");
        } catch (Exception e){
            e.printStackTrace();
            return ResultBO.fail("添加定时任务失败!");
        }
    }
    
    @Override
	public ResultBO updateQuartzJob(AddRequest addRequest) throws Exception {
    	TaskEntity task = taskService.selectById(addRequest.getTaskId());
    	 Scheduler scheduler = schedulerFactoryBean.getScheduler();
    	 Set<JobKey> jobKeySet = scheduler.getJobKeys(GroupMatcher.anyGroup());
		/*
		 * List<TimeTaskEntity> timedTaskList = selectByTaskId(task.getId());
		 * for(TimeTaskEntity timedTask : timedTaskList){ Calendar calendar =
		 * scheduler.getCalendar(timedTask.getName());
		 * 
		 * }
		 * 
		 * SimpleTrigger trigger = (SimpleTrigger)
		 * sched.getTrigger(jobName,TRIGGER_GROUP_NAME); if (trigger == null) { return;
		 * } Date oldTime = trigger.getStartTime(); if (!oldTime.equals(time)) {
		 * System.out.println("时间不相等，修改时间"); JobDetail jobDetail =
		 * sched.getJobDetail(jobName,JOB_GROUP_NAME); Class objJobClass =
		 * jobDetail.getJobClass(); removeJob(jobName); addJob(jobName, objJobClass,
		 * time); }
		 */

	 
		return null;
	}

	@Override
	public ResultBO selectQuartzJobList(AddRequest addRequest) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	

    /**
     * 第一次提醒
     */
    public void addOneTime(AddRequest request, TaskEntity task) {

    	TimeTaskEntity timedTask = new TimeTaskEntity();
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(DateUtil.timeToCron(request.getOneTime()));
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("oneTime1" + task.getId(), "remind")
                .withSchedule(cronScheduleBuilder)
                .usingJobData("taskId", task.getId())
                .usingJobData("taskName", task.getName())
                .usingJobData("execution", request.getOneTime())
                .build();

        JobDetail jobDetail = JobBuilder.newJob(RemindJob.class)
                .usingJobData("taskId", task.getId())
                .usingJobData("taskName", task.getName())
                .usingJobData("execution", request.getOneTime())
                .withIdentity("oneTime1" + task.getId(), "remind")
                .storeDurably()
                .build();

        try {
            // 如果任务存在了就删除掉
            if (scheduler.checkExists(jobDetail.getKey())) {
                scheduler.deleteJob(jobDetail.getKey());
            }

            timedTask.setTaskId(task.getId());
            timedTask.setCron(DateUtil.timeToCron(request.getOneTime()));
            timedTask.setName(task.getName());
            timedTask.setJobGroup("remind");
            timedTask.setCreateTime(new Date());
            timedTask.setDeleteFlag(0);
            timedTask.setExecutionTime(DateUtil.timeToDate(request.getOneTime()));
            this.insert(timedTask);
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 第二次提醒
     */
    public void addTwoTime(AddRequest request, TaskEntity task) {

        String time = request.getThirdTime();
        Integer taskId = task.getId();
        String taskName = task.getName();

        TimeTaskEntity timedTask = new TimeTaskEntity();
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(DateUtil.timeToCron(time));
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(taskName, "remind")
                .withSchedule(cronScheduleBuilder)
                .usingJobData("taskId", taskId)
                .usingJobData("taskName", taskName)
                .build();

        JobDetail jobDetail = JobBuilder.newJob(RemindJob.class)
                .usingJobData("taskId", taskId)
                .usingJobData("taskName", taskName)
                .withIdentity(taskName, "remind")
                .storeDurably()
                .build();

        try {
            // 如果任务存在了就删除掉
            if (scheduler.checkExists(jobDetail.getKey())) {
                scheduler.deleteJob(jobDetail.getKey());
            }
            timedTask.setTaskId(taskId);
            timedTask.setCron(DateUtil.timeToCron(time));
            timedTask.setName(taskName);
            timedTask.setJobGroup("remind");
            timedTask.setCreateTime(new Date());
            timedTask.setDeleteFlag(0);
            timedTask.setExecutionTime(DateUtil.timeToDate(time));
            this.insert(timedTask);
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 第三次提醒
     */
    public void addThirdTime(AddRequest request, TaskEntity task) {
        String time = request.getThirdTime();
        Integer taskId = task.getId();
        String taskName = task.getName();

        TimeTaskEntity timedTask = new TimeTaskEntity();
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(DateUtil.timeToCron(time));
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(taskName, "remind")
                .withSchedule(cronScheduleBuilder)
                .usingJobData("taskId", taskId)
                .usingJobData("taskName", taskName)
                .build();

        JobDetail jobDetail = JobBuilder.newJob(RemindJob.class)
                .usingJobData("taskId", taskId)
                .usingJobData("taskName", taskName)
                .withIdentity(taskName, "remind")
                .storeDurably()
                .build();

        try {
            // 如果任务存在了就删除掉
            if (scheduler.checkExists(jobDetail.getKey())) {
                scheduler.deleteJob(jobDetail.getKey());
            }

            scheduler.scheduleJob(jobDetail, trigger);
            timedTask.setTaskId(taskId);
            timedTask.setCron(DateUtil.timeToCron(time));
            timedTask.setName(taskName);
            timedTask.setJobGroup("remind");
            timedTask.setCreateTime(new Date());
            timedTask.setDeleteFlag(0);
            timedTask.setExecutionTime(DateUtil.timeToDate(time));
            this.insert(timedTask);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除定时任务
     * @param task
     * @return
     */
    private ResultBO deleteQuartz(TaskEntity task) throws Exception{

        ResultBO resultBO = new ResultBO();
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        List<TimeTaskEntity> timedTaskList = selectByTaskId(task.getId());
        for(TimeTaskEntity timedTask : timedTaskList){
            scheduler.deleteJob(JobKey.jobKey(timedTask.getName(), "remind"));
        }
        resultBO.setSucceed(true);
        resultBO.setMsg("删除定时任务成功!");
        resultBO.setCode(200);
        return resultBO;
    }

    /**
     * 根据任务id查询定时任务列表
     * @param id
     * @return
     */
    private List<TimeTaskEntity> selectByTaskId(Integer id) {

        List<TimeTaskEntity> timedTasks = null ;
        // timedTaskMapper.selectByTaskId(id);
        return timedTasks;
    }

	@Override
	public ResultBO demo() throws Exception {
		String table =null;
		String flag = "1";
		if("1".equals(flag)) {
			table ="user";
		}else {
			table = "user_01";
		}
		
		AddRequest request = new  AddRequest();
		request.setOneName("张三");
		request.setOneTime("2021-12-01 00:00:00")
		;
		TaskEntity task = new TaskEntity();
		task.setName("李四");
		task.setId(1);
		task.setCreateTime(new Date());
		task.setTableName(table);
		
	
		JobUtils.setJobSchedulerFactory(UserJob.class, schedulerFactoryBean, request, task);
		
		TimeTaskEntity timedTask = new TimeTaskEntity();
		timedTask.setTaskId(1);
        timedTask.setCron(DateUtil.timeToCron("2021-12-01 00:00:00"));
        timedTask.setName("李四");
        timedTask.setJobGroup("remind");
        timedTask.setCreateTime(new Date());
        timedTask.setDeleteFlag(0);
        timedTask.setExecutionTime(DateUtil.timeToDate(DateUtil.getYestoday()));
        this.insert(timedTask);
        
        return ResultBO.success("添加定时任务成功!");
	}

}
